<?php
/*
 * 分站的处理
 * @package    city
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 8408a28a07045c09b47e494eba670709ce091d00 $
 */
require 'common.inc.php';
$DT['city'] or dheader(SITE_URL);
if ($action != 'go'){
	Cookie::set('jumpUrl', Env::referer());
}

if($action == 'go') {
	if(isset($auto)) {
		if($DT['city_ip']) {
			Cookie::set('city', '');
		} else {
			$iparea = Area::ip2area($DT_IP);
			$result = $db->query("SELECT * FROM {$db->getPre()}city");
			while($r = $db->fetchArray($result)) {
				if(preg_match("/".$r['name'].($r['iparea'] ? '|'.$r['iparea'] : '')."/i", $iparea)) {
					if($r['domain']) {
						dheader($r['domain']);
					} else {
						Cookie::set('city', $r['areaid'].'|'.$r['domain'], $DT_TIME + 365*86400);
					}
					break;
				}
			}
		}
		dheader(SITE_URL);
	}

	$areaid = isset($areaid) ? intval($areaid) : 0;
	if($areaid) {
		$r = $db->getOne("SELECT areaid,name,domain,template FROM {$db->getPre()}city WHERE areaid=$areaid");
		if($r) {
			Cookie::set('city', $r['areaid'].'|'.$r['domain'], $DT_TIME + 365*86400);
			$url = '';
			if (Cookie::has('jumpUrl')) {
				$forward =Cookie::get('jumpUrl');
				Cookie::remove('jumpUrl');
			}

			if($forward) {
				if(strpos($forward, $CFG['domain']) !== false) {
					if($r['domain']) {
						$url = str_replace(SITE_URL, $r['domain'], $forward);
					} else {
						$url = $forward;
					}

				} else if($city_domain && strpos($forward, $city_domain) !== false) {
					if($r['domain']) {
						$url = str_replace($city_domain, $r['domain'], $forward);
					} else {
						$url = str_replace($city_domain, SITE_URL, $forward); //For Module Subdomain
					}
				}
			}
			if(strpos($url, 'city.php') !== false) $url = '';
			dheader($url ? $url : SITE_URL);
		}
	}
	Cookie::set('city', '0|', $DT_TIME + 365*86400);
	dheader(SITE_URL);
}
if (!isset($cityFilter)) {
	$cityFilter = 'alphabet';
}
if ($cityFilter == 'alphabet') {
	$lists = City::listsByABC();
} elseif ($cityFilter == 'province') {
	$lists = City::listsByArea();
}
$head_title = $L['citytitle'];
include template('city', 'city');